package com.my.lucky.repository;

import com.my.lucky.entity.SysInfo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

@Repository
public interface SysInfoRepository extends JpaRepository<SysInfo, Long> {

    @Query("SELECT sys FROM SysInfo sys")
    List<SysInfo> findAllBy();

    // 更新操作
    @Modifying
    @Transactional
    @Query("UPDATE SysInfo s SET s.sysValue = ?2 WHERE s.sysKey = ?1")
    int updateByKey(String key, String value);


    // 更新操作：在原有sysValue后追加新值
    @Modifying
    @Transactional
    @Query("UPDATE SysInfo s SET s.sysValue = CONCAT(s.sysValue, ?2) WHERE s.sysKey = ?1")
    int appendByKey(String key, String value);

    @Modifying
    @Transactional
    @Query("UPDATE SysInfo s SET s.sysValue = REPLACE(s.sysValue, ?2, '') WHERE s.sysKey = ?1")
    int removeByKey(String key, String value);

    // 根据 sysKey 和 types 查询
    @Query("SELECT s FROM SysInfo s WHERE s.sysKey = ?1 AND s.types = ?2")
    SysInfo findBySysKeyAndTypes(String sysKey, Integer types);

    @Query("SELECT s FROM SysInfo s WHERE s.types = ?1")
    List<SysInfo> findByTypes(Integer types);

    // 根据 sysKey 和 types 更新 sysValue
    @Modifying
    @Transactional
    @Query("UPDATE SysInfo s SET s.sysValue = ?3, s.createTime = CURRENT_TIMESTAMP WHERE s.sysKey = ?1 AND s.types = ?2")
    int updateBySysKeyAndTypes(String sysKey, Integer types, String sysValue);

}
